# handle_mock
# 2024/10/24
# author:www
import threading
import time

import requests

# def get_re(timeout = 30):
#     # 获取当前时间(s)
#     start_time = time.time()
#     end_time = start_time + timeout
#     count = 0
#     # 如果当前时间未超过结束时间，一直发送请求
#     while time.time() < end_time:
#         resp = requests.get('http://127.0.0.1:5000/health')
#         # 每请求一次就记录一次
#         count += 1
#         if resp.text:
#             print(f'第{count}次查询，返回了结果：',resp.text)
#             break
#         # 间隔3秒发一次请求
#         time.sleep(3)
#     return resp.json()


host = 'http://127.0.0.1:9990'


def t1est001(indata):
    '''
    新增结果词接口
    :param indata: 请求内容
    :return: json响应结果
    '''
    url = f'{host}/phis/health/reportWord/saveOrUpdateByEntity'
    res = requests.post(url, json=indata)
    return res.json()


def t1est002(indata, interval=2, timeout=10):
    '''
    1、使用新增接口返回的id查询
    2、查询次数-频率3秒查一次
    3、设置超时时间，30s未查到超时
    :param resultwords_id: 查询id
    :param interval: 查询频率
    :param timeout: 超时时间
    :return:res.text响应结果用text可以避免未查到，转json报错
    '''
    start_time = time.time()
    end_time = start_time + timeout
    count = 0
    # 判断当前时间是否小于结束时间
    url = f'{host}/phis/health/reportWord/getPage1'
    while time.time() < end_time:
        res = requests.post(url, json=indata)
        # 每请求一次记录一次
        count += 1
        # 判断是否有响应数据返回，如果有直接结束循环
        if res.text:
            print(f'第{count}次查询，返回了结果：', res.text)
            break
        # 如果请求一次后未找到，就休息5秒，再发送请求
        else:
            print(f'第{count}次查询，未找到结果！！！')
            # 强制等待，代码不会再去处理其他的事情；
            # 导致问题：io阻塞，cpu密集型
            # 解决方案：
            time.sleep(interval)
    print('查询结束！！！')
    return res.text


if __name__ == '__main__':
    # 计时执行
    start_time = time.time()
    data_1 = {
        "id": 123,
        "resultWord": "test",
        "abbr": "hh",
        "reason": "hhh",
        "suggest": "testdrink"
    }
    data_2 = {
        "current": 1,
        "pageSize": 15,
        "condition": {
            "resultWord": ""
        }
    }
    res_01 = t1est001(data_1)['resultWord']
    data_2['condition']['resultWord'] = res_01
    # res_02 = t1est002(data_2)
    print(res_01)
    t1 = threading.Thread(target=t1est002, args=(data_2,))
    # 主线程结束，子线程退出
    t1.daemon = True
    t1.start()

    for i in range(1,10):
        time.sleep(1)
        print(f'循环次数{i},验证线程！！！')

    end_time = time.time()
    print('执行结束时间：',end_time - start_time)
